package com.central.user.controller;

import com.central.common.annotation.LoginUser;
import com.central.common.annotation.RequiredPermission;
import com.central.common.constant.PermissionConstants;
import com.central.common.model.Result;
import com.central.common.model.SysDepartment;
import com.central.common.model.SysUser;
import com.central.user.service.ISysDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Tindy
 * @date 2021/6/22
 * @describe
 */
@RestController
@Api(tags = "部门模块api")
@Slf4j
@RequestMapping("/department")
public class SysDepartmentController {
    @Autowired
    private ISysDepartmentService departmentService;


    /**
     * 递归循环实现建树
     *
     * @param departments
     * @return
     */
    public void treeBuilder(List<SysDepartment> departments) {
        for (SysDepartment department : departments) {
            List<SysDepartment> subs = departmentService.findSubs(department.getId());
            treeBuilder(subs);
            department.setSubs(subs);
        }
    }

    /**
     * 删除部门
     *
     * @param id
     */
    @ApiOperation(value = "删除部门")
    @DeleteMapping("/{id}")
    @CacheEvict(value =  {"departmentsTree","departmentMap"},allEntries=true)
    @RequiredPermission({PermissionConstants.SYS_ADMIN})
    public Result delete(@PathVariable Long id) {
        try {
            departmentService.removeById(id);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("department-delete-error", ex);
            return Result.failed("操作失败:"+ex.getMessage());
        }
    }

    @ApiOperation(value = "获取一级部门")
    @GetMapping("/findOnes")
    public List<SysDepartment> findOnes() {
        return departmentService.findOnes();
    }


    /**
     * 添加部门
     *
     * @param department
     * @return
     */
    @ApiOperation(value = "新增部门")
    @PostMapping("create")
    @CacheEvict(value =  {"departmentsTree","departmentMap"},allEntries=true)
    @RequiredPermission({PermissionConstants.SYS_ADMIN})
    public Result create(@RequestBody SysDepartment department) {
        try {
            department.setId(null);
            SysDepartment parentDepartment = departmentService.getById(department.getParentId());
            List<Long> parentIds;
            if(parentDepartment==null){
                parentIds=new ArrayList<>();
            }else {
                parentIds = parentDepartment.getParentIds();
            }
            parentIds.add(department.getParentId());
            department.setParentIds(parentIds);
            departmentService.save(department);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("department-create-error", ex);
            return Result.failed("操作失败");
        }
    }

    /**
     * 修改部门名
     *
     * @param departmentId
     * @param newName
     * @return
     */
    @ApiOperation(value = "修改部门名")
    @GetMapping("/editName")
    @CacheEvict(value = {"departmentsTree","departmentMap"},allEntries=true)
    @RequiredPermission({PermissionConstants.SYS_ADMIN})
    public Result editName(Long departmentId,String newName) {
        try {
            SysDepartment department = departmentService.getById(departmentId);
            department.setName(newName);
            departmentService.saveOrUpdate(department);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("department-editName-error", ex);
            return Result.failed("操作失败");
        }
    }
    /**
     * 当前登录用户的部门
     *
     * @return
     */
    @GetMapping("/current")
    @ApiOperation(value = "查询当前用户部门")
    public SysDepartment findMyDepartment(@ApiIgnore @LoginUser SysUser user) {
        SysDepartment department = departmentService.findByUserId(user.getId());
        return department;
    }

    @GetMapping("/fullName")
    @ApiOperation(value = "查询部门全名")
    public String fullName(Long departmentId){
        return departmentService.fullName(departmentId);
    }

    @GetMapping("/findAll")
    @ApiOperation(value = "查询所有部门树")
    @Cacheable(value = "departmentsTree")
    public List<SysDepartment> findAll(){
        List<SysDepartment> departments = departmentService.findOnes();
        treeBuilder(departments);
        return departments;
    }

    @GetMapping("/findDepartmentMap")
    @ApiOperation(value = "获取部门字典")
    @Cacheable(value = "departmentMap")
    public Map<String,SysDepartment> findDepartmentMap(){
        Map<String,SysDepartment> map = departmentService.findDepartmentMap();
        return map;
    }
}
